<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\web\controller;

use app\common\Base;
use app\web\controller\Contest;
/**
 * Description of contestdiscuss
 *
 * @author wurong
 */


// 关于比赛讨论的 类

class Contestdiscuss extends Base{
    private $cid=0;
    public function __construct() {
        parent::__construct();
        $this->cid=input('cid',0,'intval');
        $this->judge($this->cid);
        $contest_info= $this->judge_contest_exist($this->cid);
        if($contest_info==false){
            $this->error_ui('该比赛不存在');
        }
        $list=db('contest')->where(['contest_id'=> $this->cid])->select();
        $this->assign('list',$list);
        $this->assign('cid', $this->cid);
        $now_time = date('Y-m-d H:i:s',time());  //获取当前时间（日期形式）
        $seal_time = $list[0]['seal_time'];
        $unmake_time = $list[0]['unmake_time'];
        $seal = false;
        if(strcmp($now_time,$seal_time)>0 && strcmp($now_time,$unmake_time)<0) $seal=true;
        $this->assign('seal', $seal);
        $this->assign('is_contest_create', $this->is_contest_create());
        $this->assign('is_contest_admin', $this->have_power(4)||$this->have_power(3));
        $this->assign('timeleft', $this->get_contest_left_time($this->cid));
    }

    private function is_contest_create(){
        $cid= input('cid',null);
        if($cid==null) return false;
        $info=db('contest')->find($cid);
        if(empty($info)){
            return false;
        }
        if($info['user_id']== $this->user_id) {
            return true;
        }else {
            return FALSE;
        }
    }
    private function cut_str($string, $sublen, $start = 0, $code = 'UTF-8') {
        if ($code == 'UTF-8') {
            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            preg_match_all($pa, $string, $t_string);

            if (count($t_string[0]) - $start > $sublen)
                return join('', array_slice($t_string[0], $start, $sublen)) . "...";
            return join('', array_slice($t_string[0], $start, $sublen));
        }
        else {
            $start = $start * 2;
            $sublen = $sublen * 2;
            $strlen = strlen($string);
            $tmpstr = '';

            for ($i = 0; $i < $strlen; $i++) {
                if ($i >= $start && $i < ($start + $sublen)) {
                    if (ord(substr($string, $i, 1)) > 129) {
                        $tmpstr .= substr($string, $i, 2);
                    } else {
                        $tmpstr .= substr($string, $i, 1);
                    }
                }
                if (ord(substr($string, $i, 1)) > 129)
                    $i++;
            }
            if (strlen($tmpstr) < $strlen)
                $tmpstr .= "...";
            return $tmpstr;
        }
    }

    public function index(){
        $cid= $this->cid;
        $num= input('num',-2,'intval');
        $contest_info= $this->judge_contest_exist($cid);
        if($contest_info==false){
            $this->error_ui('该比赛不存在');
        }
        $problems=db('contest_problem')->where(['contest_id'=>$cid])->order('num ASC') ->select();
        foreach ($problems as $k=>$v){
            $problems[$k]['no']= $this->get_char($k);
        }
        $condition['pre']=['in',[-1,-2]];
        $condition['cid']=$cid;
        if($num!=null&&$num!=-2){
            $condition['num']=$num;
        }
        $discuss=db('contest_discuss')->where($condition)->order('reply_time DESC')->paginate();
        $page=$discuss->render();
        $discusslist=$discuss->toArray()['data'];
        foreach ($discusslist as $k=>$v){
            $discusslist[$k]['summary']= $this->cut_str(strip_tags($v['content']), 20);
        }
        $this->assign('problemlist',$problems);
        $this->assign('select_num',$num);
        $this->assign('discusslist',$discusslist);
        $this->assign('page',$page);
        $this->assign('cid',$cid);
        return $this->fetch();
    }
    private function judge_contest_exist($cid){
        $res= db('contest')->where(['defunct'=>'N'])->find($cid);
        if(empty($res)) {
            return false;
        }
        else {
            return $res;
        }
    }
    
    private function getlabel($num,$cid){
        if($num==-1) return 'public 通用提问';
        $condition['contest_id']=$cid;
        $condition['num']=$num;
        $res=db('contest_problem')->where($condition)->find();
        if(empty($res)) {
            return $this->get_char($num);
        }
        if($res['alias']=='') {
            return $res['problem_title'];
        }
        else {
            return $res['alias'];
        }
    }
    private function is_tongzhi($id){
        $res=db('contest_discuss')->find($id);
        if(empty($res)){
            return false;
        }
        //dump($res);
        if($res['pre']==-2){
            return '通知-管理员';
        }
        else {
            return FALSE;
        }
    }

    public function post_discuss(){
        $cid= $this->cid;
        $problems=db('contest_problem')->where(['contest_id'=>$cid])->order('num ASC') ->select();
        foreach ($problems as $k=>$v){
            $problems[$k]['no']= $this->get_char($k);
        }
        $this->assign('problemlist',$problems);
        
        $this->assign('cid',$cid);
        return $this->fetch();
    }
    private function deal_discuss_data($cid,$num,$content){
        $data['pre']=-1;
        $data['cid']=$cid;
        $data['num']=$num;
        $data['user_id']= $this->user_id;
        $data['in_time']=time();
        $data['content']=$content;
        $data['reply_time']=$data['in_time'];
        $data['ip']= request()->ip();
        return $data;
    }

    public function do_post_discuss(){
        $cid= input('cid',null,'intval');
        $num= input('num',null,'intval');
        $content= $this->remove_xss(input('content',null,'trim'));
        if($cid==null||$num==$content||$num==null){
            $this->error_ui('内容不可为空');
        }
        if(!$this->is_login){
            $this->error('请登录');
        }
        
        $id=db('contest_discuss')->insertGetId($this->deal_discuss_data($cid, $num, $content));
        if($id==false){
            $this->error_ui('发布失败,未知错误');
        }
        $this->success_ui('提问成功', url('web/Contestdiscuss/show',['id'=>$id,'cid'=>$cid]));
    }
    public function show(){
        $id= input('id',0,'intval');
        $res=db('contest_discuss')->find($id);
        if(empty($res)){
            $this->error_ui('对不起,该讨论不存在');
        }
        $this->assign('discuss',$res);
        $this->assign('id',$id);
        $label= $this->is_tongzhi($id);
        if($label==FALSE){
            $label=$this->getlabel($res['num'], $this->cid);
        }
        $this->assign('label', $label);
        return $this->fetch();
    }
    public function getmorereply(){
        $id=input("id",null,'intval');
        $page= input('page',1,'intval');
        $cid= $this->cid;
        $condition['cid']=$cid;
        $condition['pre']=$id;
        $list=db('contest_discuss')->where($condition)->limit(($page-1)* config('community.pagenum'),config('community.pagenum'))->order('in_time DESC')->select();
        $count=db('contest_discuss')->where($condition)->count();
        $res['pages'] = ceil($count / config('community.pagenum'));
        $this->assign('discuss',$list);
        $res['html']= $this->fetch();
        return json($res);
    }   
    
    public function post_reply(){
        if(!$this->is_login){
            $this->error_ui('请先登录');
        }
        $id=input('id',null,'intval');
        $cid= $this->cid;
        $content= input('content',null,'trim');
        if($id==null||$content==null){
            $this->error_ui('回复内容不能为空哦~');
        }
        $data['pre']=$id;
        $data['cid']= $this->cid;
        $data['num']=-1;
        $data['user_id']= $this->user_id;
        $data['in_time']=time();
        $data['content']= $this->remove_xss($content);
        $data['ip']= request()->ip();
        $data['reply_time']=$data['in_time'];
        db('contest_discuss')->insert($data);
        db('contest_discuss')->where('id='.$id)->update(['reply_time'=>$data['in_time']]);
        $this->success_ui('回复成功', url('web/Contestdiscuss/show',['id'=>$id,'cid'=>$cid]));
    }
}
